import superagent from 'superagent';

const methods = [
    'get',
    'head',
    'post',
    'put',
    'del',
    'options',
    'patch'
];

class _Api {
    constructor(opts) {
        this.opts = opts || {};

        if (!this.opts.baseURI)
            throw new Error('baseURI option is required');

        methods.forEach(method =>
            this[method] = (path, {params, data} = {}) => new Promise((resolve, reject) => {
                const request = superagent[method](this.opts.baseURI + path);
                request.withCredentials();
                if (params) {
                    request.query(params);
                }

                if (this.opts.headers) {
                    request.set(this.opts.headers);
                }

                if (data) {
                    request.send(data);
                }
                request.end(function (err, res) {
                    console.log(res.header);
                    return err ? reject(res.body || err) : resolve(res.body);
                });
                //request.end((err, {body} = {}, {headers} = {}) => err ? reject(body || err, headers) : resolve(body, headers));
            })
        );
    }
}
const Api = _Api;
export default Api;
